import _ from 'lodash';
import {API_URL} from '../constants';
import {message} from 'antd';

export default (modName) => {
  return (action, settings) => {
    const defaultSettings = {
      type: 'json',
      successTip: '',
      ignoreError: false,
      credentials: "include"
    };

    return new Promise((res, rej) => {
      let url = '';

      if (_.isObject(action)) {
        settings = action;
        url = settings.url;
      } else {
        url = `${API_URL}${modName}/${action}`;
      }

      settings = Object.assign(defaultSettings, settings);

      fetch(url, settings).then(response => {
        response.text().then(responseText => {
          if ('json' === settings.type) {
            const result = JSON.parse(responseText);
            try {
              if(result.api_status) {
                res(result.data);
                settings.successTip && message.success(settings.successTip)
              } else {
                const showError = !settings.ignoreError && result.api_errormsg;

                showError && message.error(result.api_errormsg);
                rej(result);
              }
            } catch(e) {
              res(result);
            }
          } else {
            res(responseText)
          }
        });
      });
    });
  }
};